import logging
from common.db_conn import DbConn

_db = None 

def init():
    '''初始化数据库'''
    logging.info("数据库初始化...")
    global _db
    _db = DbConn("data.db") 

    with _db as session:
        # create_info(session)
        # create_info_history(session)
        # create_task(session)
        # create_task_history(session)
        session.execute(info_service.CREATE_SQL)
        session.execute(info_service.CREATE_SQL_HISTORY)
        session.execute(task_service.CREATE_SQL)
        session.execute(task_service.CREATE_SQL_HISTORY)
    logging.info("数据库初始化 [ok]")

def create_info(session):
    sql ='''
    CREATE TABLE IF NOT EXISTS t_info
    (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    type    VARCHAR(32)    NOT NULL,
    content    VARCHAR(4096)    NOT NULL,
    state   INT NOT NULL,
    createTime     DATETIME     NOT NULL,
    updateTime     DATETIME     NOT NULL
    );
    '''
    session.execute(sql)

def create_info_history(session):
    sql='''
    CREATE TABLE IF NOT EXISTS t_info_history
    (
    id INT PRIMARY KEY,
    type    VARCHAR(32)    NOT NULL,
    content    VARCHAR(4096)    NOT NULL,
    state   INT NOT NULL,
    createTime     DATETIME     NOT NULL,
    updateTime     DATETIME     NOT NULL
    );
    '''
    session.execute(sql)


def create_task(session):
    sql ='''
    CREATE TABLE IF NOT EXISTS t_task
    (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    deviceName    VARCHAR(128)  DEFAULT("") NOT NULL,
    state   INT NOT NULL, -- 0 未开始  1 运行中 2 挂起 3 完成 4 失败
    stateText   VARCHAR(32)     DEFAULT("") NOT NULL,
    createTime     DATETIME     NOT NULL,
    updateTime     DATETIME     NOT NULL
    );
    '''
    session.execute(sql)

def create_task_history(session):
    sql='''
    CREATE TABLE IF NOT EXISTS t_info_history
    (
    id INT PRIMARY KEY,
    deviceName    VARCHAR(128)  DEFAULT("") NOT NULL,
    state   INT NOT NULL, -- 0 未开始  1 运行中 2 挂起 3 完成 4 失败
    stateText   VARCHAR(32)     DEFAULT("") NOT NULL,
    createTime     DATETIME     NOT NULL,
    updateTime     DATETIME     NOT NULL
    );
    '''
    session.execute(sql)


def db():
    return _db











import service.task.task_service as task_service
import service.info.info_service as info_service